package com.bp.hearthealth.pulse.lnapps.ads.topon.native_ad

import com.anythink.core.api.ATAdConst
import com.anythink.core.api.ATAdInfo
import com.anythink.core.api.AdError
import com.anythink.nativead.api.ATNative
import com.anythink.nativead.api.ATNativeAdView
import com.anythink.nativead.api.ATNativeDislikeListener
import com.anythink.nativead.api.ATNativeEventExListener
import com.anythink.nativead.api.ATNativeNetworkListener
import com.anythink.nativead.api.NativeAd
import com.bp.hearthealth.pulse.lnapps.BpApplication
import com.bp.hearthealth.pulse.lnapps.ads.admob.native_ad.AdMobNativeAdManager
import com.bp.hearthealth.pulse.lnapps.ads.model.AdsCount
import com.bp.hearthealth.pulse.lnapps.ads.model.AdsSwitch
import com.bp.hearthealth.pulse.lnapps.ads.topon.interstitial_ad.TopOnInterAdManager
import com.bp.hearthealth.pulse.lnapps.bp_extension.LogUtil
import com.bp.hearthealth.pulse.lnapps.bp_utils.Constants
import com.bp.hearthealth.pulse.lnapps.bp_utils.DateUtils
import java.util.Timer
import java.util.TimerTask


object TopOnNativeAdManager {

    var atNative: ATNative? = null
    var mNativeAd: NativeAd? = null
    private var adListener: TopOnNativeAdListener? = null
    private var loading = true
    private var nativeAds: MutableList<NativeAd> = mutableListOf()
    private var onRefresh = true

    fun initATNativeAd() {
        if (atNative == null) {
            //初始化广告加载对象
            atNative = ATNative(
                BpApplication.context,
                Constants.TOP_ON_NATIVE_ID,
                object : ATNativeNetworkListener {
                    override fun onNativeAdLoaded() {
                        LogUtil.iTopOn("TopOn 【原生广告】 ~~~~ 【结束时间】： ${DateUtils.nowTime(System.currentTimeMillis())}")
                        loading = false
                        onRefresh = true
                        setListener()
                        adListener?.onNativeAdLoaded()
                        LogUtil.iTopOn("TopOn 【原生广告】 onNativeAdLoaded isReady：${atNative!!.checkAdStatus().isReady}, adListener = $adListener")
                    }

                    override fun onNativeAdLoadFail(adError: AdError) {
                        loading = true
                        if (onRefresh) {
                            onRefresh = false
                            //延迟10秒加载
                            Timer().schedule(object : TimerTask() {
                                override fun run() {
                                    loadAd()
                                    LogUtil.iTopOn("TopOn 【原生广告】 加载失败 延迟10s后重新请求 插页广告。。。。。。。。")
                                }
                            }, 10000)
                        }
                        adListener?.onNativeAdLoadFail()
                        LogUtil.iTopOn("TopOn 【原生广告】 onNativeAdLoadFail isReady：${atNative!!.checkAdStatus().isReady}")
                        LogUtil.iTopOn("TopOn 【原生广告】 onNativeAdLoadFail ${adError.fullErrorInfo}")
                    }
                })
        }
    }

    fun releaseNativeAd() {
        destroyAd()
        if (atNative != null) {
            atNative!!.setAdListener(null)
            atNative!!.setAdSourceStatusListener(null)
        }
    }

    fun destroyAd() {
        if (mNativeAd != null) {
            mNativeAd!!.destory()
        }
    }

    fun removeUsedNativeAdListener() {
        setNativeAdListener(null)
        if (!loading) {
            LogUtil.iTopOn("TopOn 【原生广告】 移除监听，加载原生广告")
            loadAd()
            loading = true
        }
    }

    fun loadAd() {
//        if (adListener != null && !AdsSwitch.getBoolean(AdsSwitch.adNativeControl)) {
//            LogUtil.iTopOn("TopOn 【原生广告】 开关状态：${AdsSwitch.getBoolean(AdsSwitch.adNativeControl)}")
//            adListener!!.onFireBaseAdIsClosed()
//            return
//        }
//        if (!AdsSwitch.getBoolean(AdsSwitch.adNativeControl)) {
//            LogUtil.iTopOn("TopOn 【原生广告】 开关状态：${AdsSwitch.getBoolean(AdsSwitch.adNativeControl)}")
//            return
//        }
        val localExtra: MutableMap<String, Any> = java.util.HashMap()
//        localExtra[ATAdConst.KEY.AD_WIDTH] = adViewWidth
//        localExtra[ATAdConst.KEY.AD_HEIGHT] = 20
        atNative?.setLocalExtra(localExtra)
        LogUtil.iTopOn("TopOn 【原生广告】 ~~~~ 【开始时间】： ${DateUtils.nowTime(System.currentTimeMillis())}")
        atNative?.makeAdRequest()
    }

    fun getNativeAds(): MutableList<NativeAd> {
        if (!AdsSwitch.getBoolean(AdsSwitch.adNativeControl)) {
            return mutableListOf()
        }
        return nativeAds
    }

    fun isAdReady(): Boolean {
        if (adListener != null && !AdsSwitch.getBoolean(AdsSwitch.adNativeControl)) {
            return false
        }
        return atNative?.checkAdStatus()?.isReady == true
    }

    fun setNativeAdListener(listener: TopOnNativeAdListener?) {
        adListener = listener
        /*if (listener != null && !AdsSwitch.getBoolean(AdsSwitch.adNativeControl)) {
            listener.onFireBaseAdIsClosed()
            return
        }*/
    }

    private fun releaseNativeAds() {
        if (nativeAds.isNotEmpty()) {
            val iterator = nativeAds.iterator()
            while (iterator.hasNext()) {
                val ad = iterator.next()
                ad.destory()
                iterator.remove()
            }
        }
        if (atNative!=null) {
            atNative!!.setAdListener(null)
            atNative!!.setAdSourceStatusListener(null)
            atNative= null
        }
    }

    /**
     * 移除当前页原生广告对象
     * 当前页销毁时调用
     */
    fun removeUsedNativeAd(nativeAd: NativeAd) {
        setNativeAdListener(null)
        nativeAd.destory()
        nativeAds.remove(mNativeAd)
        LogUtil.iTopOn("TopOn 【原生广告】 移除监听，nativeAds.size = ${nativeAds.size}")
        if (nativeAds.isEmpty() && !loading) {
            loadAd()
            loading = true
        }
    }

    fun release() {
        setNativeAdListener(null)
        releaseNativeAds()
    }

    private fun setListener() {
        val nativeAd: NativeAd? = atNative?.nativeAd
        if (nativeAd != null) {
            if (mNativeAd != null) {
                mNativeAd!!.destory()
            }
            mNativeAd = nativeAd
            nativeAds.add(0, mNativeAd!!)
            mNativeAd!!.setNativeEventListener(object : ATNativeEventExListener {
                override fun onDeeplinkCallback(
                    view: ATNativeAdView,
                    adInfo: ATAdInfo,
                    isSuccess: Boolean
                ) {
                    adListener?.onDeeplinkCallback(view, adInfo, isSuccess)
                    LogUtil.iTopOn(
                        "TopOn 【原生广告】 onDeeplinkCallback:$adInfo--status:$isSuccess"
                    )
                }

                override fun onAdImpressed(view: ATNativeAdView, entity: ATAdInfo) {
                    adListener?.onAdImpressed(view, entity)
                    LogUtil.iTopOn("TopOn 【原生广告】 native ad onAdImpressed:\n$entity")
                }

                override fun onAdClicked(view: ATNativeAdView, entity: ATAdInfo) {
                    AdsCount.incrementClickCount()
                    adListener?.onAdClicked(view, entity)
                    LogUtil.iTopOn("TopOn 【原生广告】 native ad onAdClicked:\n$entity")
                }

                override fun onAdVideoStart(view: ATNativeAdView) {
                    adListener?.onAdVideoStart(view)
                    LogUtil.iTopOn("TopOn 【原生广告】 native ad onAdVideoStart")
                }

                override fun onAdVideoEnd(view: ATNativeAdView) {
                    adListener?.onAdVideoEnd(view)
                    LogUtil.iTopOn("TopOn 【原生广告】 native ad onAdVideoEnd")
                }

                override fun onAdVideoProgress(view: ATNativeAdView, progress: Int) {
                    adListener?.onAdVideoProgress(view, progress)
                    LogUtil.iTopOn("TopOn 【原生广告】 native ad onAdVideoProgress:$progress")
                }
            })
            mNativeAd!!.setDislikeCallbackListener(object : ATNativeDislikeListener() {
                override fun onAdCloseButtonClick(view: ATNativeAdView, entity: ATAdInfo) {
                    adListener?.onAdCloseButtonClick(view, entity)
                    LogUtil.iTopOn("TopOn 【原生广告】 native ad onAdCloseButtonClick")
                }
            })
        }
    }
}

